package com.mtl.inmigrant.shoes;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.content.SharedPreferences;
import com.google.api.client.auth.oauth2.draft10.AccessTokenResponse;
import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAccessProtectedResource;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.plus.Plus;
import com.google.api.services.plus.model.Activity;
import com.google.api.services.plus.model.ActivityFeed;
import com.mtl.inmigrant.shoes.preferences.SharedPreferencesImmigrant;

public class ActivitiesFromGPlusHelper {
	
	private static SharedPreferencesImmigrant credentialStore;

	public static List<Activity> searchActivitiesImmigrants(SharedPreferences preferences) throws IOException {
		List<Activity> activities=null;
		JsonFactory jsonFactory = new JacksonFactory();
		HttpTransport transport = new NetHttpTransport();
		
		try {
			credentialStore = SharedPreferencesImmigrant.getInstance(preferences);
			AccessTokenResponse accessTokenResponse = credentialStore.read();
			
			if (!accessTokenResponse.accessToken.equals("")){
				GoogleAccessProtectedResource accessProtectedResource = new GoogleAccessProtectedResource(
						accessTokenResponse.accessToken, transport, jsonFactory,
						SharedPreferencesImmigrant.CLIENT_ID,
						SharedPreferencesImmigrant.CLIENT_SECRET,
						accessTokenResponse.refreshToken);

				// Set up the main Google+ class
				Plus plus = Plus.builder(transport, jsonFactory).setHttpRequestInitializer(accessProtectedResource).build();
				// Page - 103677542084050516151
				Plus.Activities.List listActivities = plus.activities().list("103677542084050516151", "public");
				listActivities.setMaxResults(25L);

				// Execute the request for the first page
				ActivityFeed activityFeed = new ActivityFeed();

				activityFeed = listActivities.execute();

				// Unwrap the request and extract the pieces we want
				activities = activityFeed.getItems();		
			}	
		} catch (IOException ex) {
			throw new IOException(ex);
		}
		return activities;
	}
	
	public static ArrayList<String> getGooglePlusActivitiesImmigrant(SharedPreferences preferences) throws IOException {
		ArrayList<String> activitiesPage=new ArrayList<String>();
		List<Activity> activities=searchActivitiesImmigrants(preferences);
		if(activities!= null && activities.size() > 0) {
			Iterator<Activity> iterator = activities.iterator();
			while (iterator.hasNext()) {
				Activity activity = (Activity) iterator.next();
				activitiesPage.add(activity.getTitle());
			}
		}
		return activitiesPage;
	}
}
